<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\User;

use App\Controller\AppBaseController;
use App\Model\Act;
use App\Model\Activity;
use App\Model\Article;
use App\Model\ArticleColumn;
use App\Model\Collect;
use App\Model\Department;
use App\Model\MultiCollect;
use App\Model\MultiComment;
use App\Model\MultiLearn;
use App\Model\MultiZan;
use App\Model\News;
use App\Model\Study;
use App\Model\Work;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\WxApiAuth;
use Hyperf\DbConnection\Db;

#[Controller(prefix: 'user')]
#[Middleware(WxApiAuth::class)]

class IndexController extends AppBaseController
{

    /**
     * 首页信息
     * @return object
     */
    #[RequestMapping(path:'indexData',methods: 'get')]
    public function indexData(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            //轮播图
            $whereBanner['status'] = 1;
            $whereBanner['is_banner'] = 1;
            $bannerList = News::where($whereBanner)
                ->selectRaw('id,type,title,photo,banner_photo,link_id,link_url,created_at')
                ->orderByDesc('id')
                ->get();

            //获取专栏
            $specialColumnList = ArticleColumn::where(['type'=>1,'is_banner'=>1])
                ->selectRaw('id,name,is_banner,banner_photo,created_at')
                ->get();

            $where['status'] = 1;
            $limit = 3;
            //获取第一资讯最新前3条
            $newsList = News::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,type,title,photo,link_id,link_url,created_at')
                ->orderByDesc('id')
                ->limit($limit)
                ->get();
            //获取第一活动最新前3条
            $actList = Act::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,type,title,photo,created_at')
                ->orderByDesc('id')
                ->limit($limit)
                ->get();
            //获取第一学习最新前3条
            $studyList = Study::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,type,title,photo,file_list,link_url,created_at')
                ->orderByDesc('id')
                ->limit($limit)
                ->get();

            //获取党务公开最新前3条
            $workList = Work::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,title,created_at')
                ->orderByDesc('id')
                ->limit($limit)
                ->get();

                //获取党务公开推送3条记录
//            $dateTime = date('Y-m-d H:i:s',time());
//            $whereWork = [
//                ['uid','=',$_user->id],
//                ['push_time','<=',$dateTime]
//            ];
//            $workList = WorkPush::with(['work'=>function($query){
//                    $query->selectRaw('id,title,photo,created_at')->get();
//                }])
//                ->where($whereWork)
//                ->selectRaw('id,work_id,uid')
//                ->orderByDesc('id')
//                ->limit($limit)
//                ->get();

            $backData = [
                'banner_list'=>$bannerList,
                'special_column_list'=>$specialColumnList,
                'news_list' => $newsList,
                'act_list' => $actList,
                'study_list' => $studyList,
                'work_list' => $workList,
            ];
            return $this->reMsg->re(1,'success',$backData);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 部门列表
     * @return object
     */
    #[RequestMapping(path:'departmentList',methods: 'get')]
    public function departmentList(): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $where['status'] = 1;
            $list = Department::where($where)
                ->orderByDesc('id')
                ->get();
            $next = 0;
            return $this->reMsg->re(1,'success',['list'=>$list,'next'=>$next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 模块页面-学习
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiLearn/{relation_id}',methods: 'post,get')]
    public function multiLearn(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr= ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'学习模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo,learn_count')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo,learn_count')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo,learn_count')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo,learn_count')->first();
            }
            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo,learn_count')->first();
            }
            if(empty($info)) return $this->reMsg->re(10008);

            $data['relation_id'] = $info->id;
            $data['module'] = $module;
            $data['uid'] = $_user->id;
            $learnInfo = MultiLearn::where($data)->first();
            if($learnInfo)  return $this->reMsg->re(10010);

            $data['title'] = $info->title;
            $data['photo'] = $info->photo;
            $data['party_id'] = $_user->party_id;

            //新建阅读记录
            $insertRet = MultiLearn::create($data);
            if($insertRet){
                //同上已经获取到 info 信息
                $info->learn_count += 1;
                $info->save();

                //加积分
                $params = [
                    'type'=> 1, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到 9:问卷 10:支部信息更新
                    'action' => 1, //action 1:加积分 2:减积分
                    'uid' => $_user->id,  //用户id
                    'party_id' => $_user->party_id  //支部id
                ];
                $this->makeIntegralLog($params);
            }
            return $this->reMsg->re(1,'学习成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面-收藏
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiCollect/{relation_id}',methods: 'post,get')]
    public function multiCollect(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if(empty($info)) return $this->reMsg->re(10008);

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['uid'] = $_user->id;
            $collectInfo = MultiCollect::where($where)->first();
            if($collectInfo){
                $collectInfo->status = 1;
                $collectInfo->save();
            }else{
                //新建
                $data['relation_id'] = $info->id;
                $data['module'] = $module;
                $data['title'] = $info->title;
                $data['photo'] = $info->photo;
                $data['uid'] = $_user->id;
                $data['party_id'] = $_user->party_id;
                MultiCollect::create($data);
            }
            return $this->reMsg->re(1,'收藏成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面-收藏-取消
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiCollectCancel/{relation_id}',methods: 'post,get')]
    public function multiCollectCancel(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if(empty($info)) return $this->reMsg->re(10008);

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['uid'] = $_user->id;
            $collectInfo = MultiCollect::where($where)->first();
            $collectInfo->status = 0;
            $collectInfo->save();

            return $this->reMsg->re(1,'取消成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面-评论
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiComment/{relation_id}',methods: 'post,get')]
    public function multiComment(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr= ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'评论模块有误');

            $content = $this->request->input('content',null);
            if(empty($content)){
                return $this->reMsg->re(10007,'评论不能为空');
            }

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo,comment_count')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo,comment_count')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo,comment_count')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo,comment_count')->first();
            }
            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo,comment_count')->first();
            }
            if(empty($info)) return $this->reMsg->re(10008);

            $insertData['module'] = $module;
            $insertData['relation_id'] = $relation_id;
            $insertData['uid'] = $_user->id;
            $insertData['content'] = $content;
            $insertData['party_id'] = $_user->party_id;
            $insertRet = MultiComment::create($insertData);
            if($insertRet){
                //同上已经获取到 info 信息
                $info->comment_count += 1;
                $info->save();

                //评论的积分前提条件式 每天只能评论5次的积分
                //查询今天已经参与了几次
                $day = date('Y-m-d',time());
                $dayStartTime = $day.' 00:00:00';
                $dayEndTime = $day.' 23:59:59';
                $where['module'] = $module;
                $where['relation_id'] = $relation_id;
                $where['uid'] = $_user->id;
                $readyCount = MultiComment::where($where)->whereBetween('created_at',[$dayStartTime,$dayEndTime])->count();
                if($readyCount<2){
                    //加积分
                    $params = [
                        'type'=> 2, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到 9:问卷 10:支部信息更新
                        'action' => 1, //action 1:加积分 2:减积分
                        'uid' => $_user->id,  //用户id
                        'party_id' => $_user->party_id  //支部id
                    ];
                    $this->makeIntegralLog($params);
                }
            }
            return $this->reMsg->re(1,'评论成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面评论列表
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiCommentList/{relation_id}',methods: 'post,get')]
    public function multiCommentList(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $list = MultiComment::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->get();
                }])
                ->selectRaw('id,uid,content,created_at')
                ->orderByDesc('id')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面-点赞
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiZan/{relation_id}',methods: 'post,get')]
    public function multiZan(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,party_id,title,photo')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,party_id,title,photo')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,party_id,title,photo')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,party_id,title,photo')->first();
            }
            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,party_id,title,photo')->first();
            }

            if(empty($info)) return $this->reMsg->re(10008);

            Db::beginTransaction();

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['uid'] = $_user->id;
            $collectInfo = MultiZan::where($where)->first();
            if($collectInfo){
                $collectInfo->status = 1;
                $collectInfo->save();
            }else{
                //新建
                $data['relation_id'] = $info->id;
                $data['module'] = $module;
                $data['title'] = $info->title;
                $data['photo'] = $info->photo;
                $data['uid'] = $_user->id;
                $data['party_id'] = $_user->party_id;
                MultiZan::create($data);

                //支部活动点赞加积分
                if($module=='activity'){
                    if($info->party_id!=null){
                        //加积分
                        $params = [
                            'type'=> 4, //积分类型 type 1:学习 2:评论 4:支部活动点赞 5:答题 6:报名 7:抽奖 8:签到 9:问卷 10:支部信息更新
                            'action' => 1, //action 1:加积分 2:减积分
                            'uid' => $_user->id,  //用户id
                            'party_id' => $info->party_id //支部id
                        ];
                        $this->makeIntegralLog($params);
                    }
                }
            }
            Db::commit();
            return $this->reMsg->re(1,'成功');
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面-点赞-取消
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiZanCancel/{relation_id}',methods: 'post,get')]
    public function multiZanCancel(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if(empty($info)) return $this->reMsg->re(10008);

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['uid'] = $_user->id;
            $collectInfo = MultiZan::where($where)->first();
            $collectInfo->status = 0;
            $collectInfo->save();

            return $this->reMsg->re(1,'取消成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 模块页面点赞列表
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'multiZanList/{relation_id}',methods: 'post,get')]
    public function multiZanList(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['status'] = 1;
            $list = MultiZan::with(['user'=>function($query){
                $query->selectRaw('id,nickname,avatar,auth_name')->get();
            }])
                ->selectRaw('id,uid,created_at')
                ->orderByDesc('id')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();
            $next = 0;
            if($list->isNotEmpty()){
                if(count($list)>=$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list, 'next' => $next]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }







    /** next old api */

    /**
     * 模块页面收藏
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'collect/{relation_id}',methods: 'post,get')]
    public function collect(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if(empty($info)) return $this->reMsg->re(10008);

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['uid'] = $_user->id;
            $collectInfo = Collect::where($where)->first();
            if($collectInfo){
                $collectInfo->status = 1;
                $collectInfo->save();
            }else{
                //新建
                $data['relation_id'] = $relation_id;
                $data['module'] = $module;
                $data['title'] = $info->title;
                $data['photo'] = $info->photo;
                $data['uid'] = $_user->id;
                $data['party_id'] = $_user->party_id;
                Collect::create($data);
            }
            return $this->reMsg->re(1,'收藏成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 模块页面收藏-取消
     * @param int $relation_id
     * @return object
     */
    #[RequestMapping(path:'collectCancel/{relation_id}',methods: 'post,get')]
    public function collectCancel(int $relation_id): object
    {
        try{
            //验证用户信息
            $checkInfo = $this->checkUser();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_user = $checkInfo['data'];

            $module = $this->request->input('module',null);
            $moduleArr = ['news','activity','study','work','article'];
            if(!in_array($module,$moduleArr)) return $this->reMsg->re(10007,'模块有误');

            $whereId['id'] = $relation_id;
            if($module=='news'){
                $info = News::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='activity'){
                $info = Activity::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='study'){
                $info = Study::where($whereId)->selectRaw('id,title,photo')->first();
            }
            if($module=='work'){
                $info = Work::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if($module=='article'){
                $info = Article::where($whereId)->selectRaw('id,title,photo')->first();
            }

            if(empty($info)) return $this->reMsg->re(10008);

            $where['module'] = $module;
            $where['relation_id'] = $relation_id;
            $where['uid'] = $_user->id;
            $collectInfo = Collect::where($where)->first();
            $collectInfo->status = 0;
            $collectInfo->save();

            return $this->reMsg->re(1,'取消成功');
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }




}